$.fn.extend({
	insertAtCaret : function(myValue) {
		if (document.selection) {
			this.focus();
			sel = document.selection.createRange();
			sel.text = myValue;
			this.focus();
		} else if (this.selectionStart || this.selectionStart == '0') {
			var startPos = this.selectionStart;
			var endPos = this.selectionEnd;
			var scrollTop = this.scrollTop;
			this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length);
			this.focus();
			this.selectionStart = startPos + myValue.length;
			this.selectionEnd = startPos + myValue.length;
			this.scrollTop = scrollTop;
		} else {
			this.value += myValue;
			this.focus();
		}
	}
});
function success(title, text) {
	var opts = {
		"closeButton" : true,
		"debug" : false,
		"positionClass" : "toast-top-full-width",
		"onclick" : null,
		"showDuration" : "300",
		"hideDuration" : "1000",
		"timeOut" : "3000",
		"extendedTimeOut" : "1000",
		"showEasing" : "swing",
		"hideEasing" : "linear",
		"showMethod" : "fadeIn",
		"hideMethod" : "fadeOut"
	};

	toastr.success(text, title, opts);

}

function errorBox(title, message) {
	var opts = {
		"closeButton" : true,
		"debug" : false,
		"positionClass" : "toast-top-full-width",
		"onclick" : null,
		"showDuration" : "300",
		"hideDuration" : "1000",
		"timeOut" : "5000",
		"extendedTimeOut" : "1000",
		"showEasing" : "swing",
		"hideEasing" : "linear",
		"showMethod" : "fadeIn",
		"hideMethod" : "fadeOut"
	};

	toastr.error(message, title, opts);
}

function shortDelete() {
	toDelete(".toDelete", function(obj) {
		var parent = $(obj).parents('.mylist');
		var u = baseAction + "delete_banner.php";
		var id = parent.attr("data");
		var d = {
			bannerID : id
		};
		initCustom(u, d, function(data) {
			if (data.SUCCESS == "true") {
				parent.fadeOut('fast', function() {
					$(this).remove();
				})
			}
		})
	})
};

function uploadInit(id, action, callback) {
	$(id).fileupload({
		url : baseAction + action,
		dataType : 'json',
		done : callback,
		progressall : function(e, data) {
			var progress = parseInt(data.loaded / data.total * 100, 10);
			$('#progress').show();
			$('#progress .progress-bar').css('width', progress + '%');
		}
	});
}

function initNormalForm(callBack, param) {
	initSubmit($('#myForm'), callBack, param);
}

function initSubmit(obj, callBack, param) {
	obj.submit(function() {
		try {
			tinymce.triggerSave();

		} catch(e) {

		}
		ajaxSetup($(this));
		if (param != undefined) {
			addParam = param;
		}
		var ele = $('textarea[rel="texteditor"]');
		var size = ele.size();
		var p = "";
		if (size > 0) {
			for ( i = 0; i < size; i++) {

				$.each(ele, function(a, b) {
					var id = $(b).attr("id");
					var name = $(b).attr("name");
					var html = CKEDITOR.instances[id].getData().replace(/&nbsp;/g, ' ');
					p += "&" + name + "=" + encodeURIComponent(html);
				});

			}

		}

		$.ajax({
			data : $(this).serialize() + p,
			success : callBack
		});

		return false;
	});
}

function ajaxSetup($this) {
	$.ajaxSetup({
		url : $this.attr("action"),
		global : false,
		type : "POST",
		data : $this.serialize(),
		dataType : 'json'
	});
}

function toDelete(cDelete, fncDelete) {

	var btnDelete = $(cDelete);
	var c = null;
	$('body').on('click', cDelete, function() {
		btnDelete.show();
		$('.cancelDelete,.confirmDelete').remove();
		var c = $(this).parent("p.confirmbox");
		var html = '<a href="#" style="margin-right:10px"  class="cancelDelete btn btn-danger btn-sm btn-icon icon-left"><i class="entypo-cancel"></i>ยกเลิก</a>';
		html += '<a href="#"  class="confirmDelete btn btn-primary btn-sm btn-icon icon-left"><i class="entypo-check"></i>ยืนยัน</a>';
		c.append(html);
		$(this).hide();
		return false;
	});

	$(document).on('click', '.cancelDelete', function() {
		$('.cancelDelete,.confirmDelete').remove();
		btnDelete.show();
		return false;
	});
	$(document).on('click', '.confirmDelete', function() {
		fncDelete(this);
		return false;
	});
}

function initCustom(u, d, callback) {
	ajaxSetupCustom(u, d,callback);
	
	
	
}

function getConfirm(btnID, title, message) {
	$('#modal').remove();

	var html = '<div class="modal fade" id="modal">';
	html += '<div class="modal-dialog">';
	html += '<div class="modal-content">';
	html += '<div class="modal-header">';
	html += '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>';
	html += '<h4 class="modal-title">' + title + '</h4>';
	html += '</div>';
	html += '<div class="modal-body">';
	html += message;
	html += '</div>';
	html += '<div class="modal-footer">';
	html += '<button id="co"' + btnID + ' type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
	html += '<button id="ca"' + btnID + ' type="button" class="btn btn-primary">Save changes</button>';
	html += '</div>';
	html += '</div>';
	html += '</div>';
	html += '</div>';
	$('body').append(html);
}

function getParameterByName(name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if (results == null)
		return "";
	else
		return results[1];
}

function urlToObj(queryString) {
	var params = {}, queries, temp, i, l;

	// Split into key/value pairs
	queries = queryString.split("&");
	// Convert the array of strings into an object
	for ( i = 0, l = queries.length; i < l; i++) {
		temp = queries[i].split('=');
		params[temp[0]] = temp[1];
	}
	return params;
};

function objectToQueryString(obj) {
	var str = [];
	for (var p in obj)
	if (obj.hasOwnProperty(p)) {
		if (p != "") {
			str.push(p + "=" + obj[p]);
		}
	}
	return str.join("&");
}

function showPopup(title, message) {

	$('#myModal h1').text(title);
	$('#myModal p').text(message);
	$('#myModal').reveal({
		animation : 'fadeAndPop', //fade, fadeAndPop, none
		animationspeed : 300, //how fast animtions are
		closeonbackgroundclick : true, //if you click background will modal close?
		dismissmodalclass : 'close-reveal-modal' //the class of a button or element that will close an open modal
	});
}

function ajaxSetupCustom(u, d, callBack) {

	$.ajaxSetup({
		url : u,
		global : false,
		type : "POST",
		data : d,
		dataType : 'json'
	});
	$.ajax({
		success : callBack
	});
}

function sivamtime() {
	now = new Date();
	hour = now.getHours();
	min = now.getMinutes();
	sec = now.getSeconds();

	if (min <= 9) {
		min = "0" + min;
	}
	if (sec <= 9) {
		sec = "0" + sec;
	}
	if (hour > 12) {
		hour = hour - 12;
		add = "pm";
	} else {
		hour = hour;
		add = "am";
	}
	if (hour == 12) {
		add = "pm";
	}

	time = ((hour <= 9) ? "0" + hour : hour) + ":" + min + ":" + sec + " " + add;
	$('#divtime').html(time);
	setTimeout("sivamtime()", 1000);
}
function fixedNumber(num){
	return num.toFixed(2); // result will equal 10.00
}
function addCommas(nStr)
{
	
	nStr = fixedNumber(nStr);
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}